<template>
  <div class="TaskBusiness">
    <!-- 弹出主体开始 -->
    <div class="infos">
      <el-dialog
        :close-on-click-modal="false"
        :title="title"
        :visible="visible"
        width="33%"
        :before-close="closeFn"
      >
        <span>
          <!-- 工单新建 -->
          <template v-if="dialogModel === 'new'">
            <el-form ref="newTaskForm" :model="newTaskForm" :rules="newTaskFormRules" label-width="140px">
              <el-form-item label="设备编号：" prop="innerCode">
                <el-input v-model.trim="newTaskForm.innerCode"
                placeholder="请输入"
                @input="newTaskUser"
                maxlength="15"
                show-word-limit
                ></el-input>
              </el-form-item>
              <el-form-item label="工单类型：" prop="productType">
                <el-select v-model="newTaskForm.productType" placeholder="请选择">
                  <el-option label="补货工单" value="2"></el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="补货数量：" class="is-required">
                <el-button
                  type="text"
                  icon="el-icon-edit-outline"
                  @click="getChannelList(newTaskForm.innerCode)"
                >
                  补货清单
                </el-button>
              </el-form-item>
              <el-form-item label="运营人员：" prop="assignorId">
                <el-select v-model="newTaskForm.assignorId" placeholder="请选择">
                  <el-option
                  v-for="item in operatorList"
                  :key="item.userId"
                  :label="item.userName"
                  :value="item.userId"
                  ></el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="备注：" prop="desc">
                <el-input type="textarea"
                v-model="newTaskForm.desc"
                placeholder="请输入备注（不超过40字）"
                maxlength="40"
                show-word-limit
                ></el-input>
              </el-form-item>
            </el-form>
          </template>
          <!-- 工单配置 -->
          <template v-if="dialogModel === 'setting'">
            <el-form
              :model="supplyAlertValue"
              ref="supplyAlertValue"
              label-width="140px"
            >
              <el-form-item
                label="补货警戒线："
                prop="number"
                :rules="[{ required: true, message: '不能为空'}]"
              >
                <el-input-number
                  v-model.number="supplyAlertValue.number"
                  controls-position="right"
                  :min="1"
                  class="number"
                ></el-input-number>
              </el-form-item>
            </el-form>
          </template>
          <!-- 查看详情 -->
          <template v-if="dialogModel === 'info'">
            <div class="showShowNeed">
              <div
                class="header"
                v-if="taksInfo.taskStatusTypeEntity?.statusId === 1"
              >
                <div class="icon">
                  <img src="@/assets/Task1-0.png" />
                </div>
                <div class="title">待办</div>
                <div class="pic">
                  <img src="@/assets/Task1-1.png" />
                </div>
              </div>
              <div
                class="header"
                v-if="taksInfo.taskStatusTypeEntity?.statusId === 2"
              >
                <div class="icon">
                  <img src="@/assets/Task1-0.png" />
                </div>
                <div class="title">进行</div>
                <div class="pic">
                  <img src="@/assets/Task1-1.png" />
                </div>
              </div>
              <div
                class="header"
                v-if="taksInfo.taskStatusTypeEntity?.statusId === 3"
              >
                <div class="icon">
                  <img src="@/assets/Task3-0.png" />
                </div>
                <div class="title">取消</div>
                <div class="pic">
                  <img src="@/assets/Task3-1.png" />
                </div>
              </div>
              <div
                class="header"
                v-if="taksInfo.taskStatusTypeEntity?.statusId === 4"
              >
                <div class="icon">
                  <img src="@/assets/Task4-0.png" />
                </div>
                <div class="title">完成</div>
                <div class="pic">
                  <img src="@/assets/Task4-1.png" />
                </div>
              </div>
              <div class="info">
                <div class="col">
                  <div class="row">
                    <div class="title">设备编号：</div>
                    <div class="col">{{ taksInfo.innerCode }}</div>
                  </div>
                  <div class="row">
                    <div class="title">创建日期：</div>
                    <div class="col">
                      {{ taksInfo.createTime?.split("T").join(" ") }}
                    </div>
                  </div>
                  <div
                    class="row"
                    v-if="taksInfo.taskStatusTypeEntity?.statusId === 4"
                  >
                    <div class="title">完成日期：</div>
                    <div class="col">
                      {{ taksInfo.updateTime?.split("T").join(" ") }}
                    </div>
                  </div>
                  <div
                    class="row"
                    v-if="taksInfo.taskStatusTypeEntity?.statusId === 3"
                  >
                    <div class="title">取消日期：</div>
                    <div class="col">
                      {{ taksInfo.updateTime?.split("T").join(" ") }}
                    </div>
                  </div>
                  <div class="row">
                    <div class="title">运营人员：</div>
                    <div class="col">{{ taksInfo.userName }}</div>
                  </div>
                  <div class="row">
                    <div class="title">工单类型：</div>
                    <div class="col">{{ taksInfo.taskType?.typeName }}</div>
                  </div>
                  <div class="row">
                    <div class="title">补货数量：</div>
                    <div class="col">
                      <el-button
                        @click.native.prevent="getTaskDetails(taksInfo.taskId)"
                        type="text"
                        size="small"
                        >补货详情</el-button
                      >
                    </div>
                  </div>
                  <div class="row">
                    <div class="title">工单方式：</div>
                    <div class="col">
                      {{ taksInfo.createType ? "手动" : "自动" }}
                    </div>
                  </div>
                  <div
                    class="row"
                    v-if="taksInfo.taskStatusTypeEntity?.statusId !== 3"
                  >
                    <div class="title">备注：</div>
                    <div class="col">{{ taksInfo.desc }}</div>
                  </div>
                  <div
                    class="row"
                    v-if="taksInfo.taskStatusTypeEntity?.statusId === 3"
                  >
                    <div class="title">取消原因：</div>
                    <div class="col">{{ taksInfo.desc }}</div>
                  </div>
                </div>
              </div>
            </div>
          </template>
        </span>
        <span slot="footer" class="dialog-footer">
          <template>
            <!-- 取消工单 -->
            <el-button
              size="medium"
              @click="closeTask(taksInfo.taskId)"
              v-if="taksInfo.taskStatusTypeEntity?.statusId === 1 && !this.reNewMode"
              >取消工单</el-button
            >
            <!-- 重新创建 -->
            <el-button
              size="medium"
              @click="reNewTask(taksInfo.taskId)"
              v-if="taksInfo.taskStatusTypeEntity?.statusId === 3 && !this.reNewMode"
              >重新创建</el-button
            >
            <!-- 普通的取消 -->
            <el-button
              size="medium"
              @click="closeFn"
              v-if="dialogModel === 'new' || dialogModel === 'setting'"
              >取消</el-button
            >
          </template>
          <!-- 新建的确定 -->
          <el-button type="primary" size="medium" v-if="dialogModel === 'new'" @click="pushTask">确定</el-button
          >
          <!-- 工单配置的确定 -->
          <el-button
            type="primary"
            size="medium"
            v-if="dialogModel === 'setting'"
            @click="settingSaveFn"
            >确定</el-button
          >
        </span>
      </el-dialog>
    </div>
    <!-- 弹出主体结束 -->
    <!-- 补货详情开始 -->
    <div class="infoMore">
      <el-dialog title="提示" :visible.sync="infoTaskShow" width="33%">
        <span>
          <div class="table" v-if="dialogModel === 'info'">
            <el-table :data="taskDetailsData" style="width: 100%" height="100%">
              <el-table-column prop="channelCode" label="货道编号">
              </el-table-column>
              <el-table-column prop="skuName" label="商品"> </el-table-column>
              <el-table-column prop="expectCapacity" label="补货数量">
              </el-table-column>
            </el-table>
          </div>
          <div class="table newTask" v-else>
            <el-table :data="tempDetails" style="width: 100%" height="100%">
              <el-table-column prop="channelCode" label="货道编号" width="92"></el-table-column>
              <el-table-column label="商品名称" width="92">
                <template slot-scope="scope">
                  <span>{{ scope.row.sku ? scope.row.sku.skuName : '-' }}</span>
                </template>
              </el-table-column>
              <el-table-column prop="currentCapacity" label="当前数量" width="92">
                <template slot-scope="scope">
                  <span>{{ scope.row.sku ? scope.row.currentCapacity : '-' }}</span>
                </template>
              </el-table-column>
              <el-table-column prop="maxCapacity" label="还可添加" width="92">
                <template slot-scope="scope">
                  <span>{{ scope.row.sku ? scope.row.maxCapacity - scope.row.currentCapacity : '-' }}</span>
                </template>
              </el-table-column>
              <el-table-column prop="maxCapacity" label="补满数量">
                <template slot-scope="scope">
                  <el-input-number
                    v-model.number="scope.row.currentCapacity"
                    controls-position="right"
                    :min="0"
                    :max="scope.row.sku ? scope.row.maxCapacity : 0"
                    class="number"
                  ></el-input-number>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </span>
        <span slot="footer" class="dialog-footer" v-if="dialogModel === 'new'">
          <el-button size="medium" @click="infoTaskShow = false">取消</el-button>
          <el-button size="medium" @click="pushTempDetails">确定</el-button>
        </span>
      </el-dialog>
    </div>
    <!-- 补货详情结束 -->
  </div>
</template>

<script>
import {
  getTaskDetails,
  taskCancel,
  supplyAlertValue,
  autoSupplyConfig,
  newTaskUser,
  getChannelList,
  postTask,
  getTaskInof
} from '@/api/taskAPIs'
export default {
  props: {
    visible: {
      type: Boolean,
      required: true
    },
    dialogModel: {
      type: String,
      required: true
    },
    taksInfo: {
      type: Object,
      required: true
    }
  },
  data () {
    return {
      title: '',
      infoTaskShow: false,
      taskDetailsData: [],
      supplyAlertValue: {
        number: 0
      },
      newTaskForm: {
        assignorId: '',
        createType: 1, // 创建类型 默认1
        innerCode: '', // 设备编号
        userId: '', // 运营人员ID
        productType: '', // 工单类型
        desc: '', // 工单描述
        details: [] // 补货信息
      },
      tempDetails: [],
      newTaskFormRules: {
        innerCode: [{ required: true, message: '设备编号不能为空' }],
        productType: [{ required: true, message: '工单类型不能为空' }],
        assignorId: [{ required: true, message: '运营人员不能为空' }],
        desc: [{ required: true, message: '备注不能为空' }]
      },
      timeOut: null, // 给防抖用（天冷多喝防冻液）
      operatorList: [], // 运营人员列
      reNewMode: false
    }
  },
  async updated () {
    // console.log(this.dialogModel)
    // 动态修改标题
    if (this.dialogModel === 'new') this.title = '新增工单'
    if (this.dialogModel === 'setting') this.title = '工单详情'
    if (this.dialogModel === 'info') this.title = '工单配置'
  },
  methods: {
    // 关闭弹框
    closeFn () {
      // 重置状态
      this.$refs.newTaskForm?.resetFields()
      this.$emit('update:visible', false)
      this.newTaskForm = {
        createType: 1,
        innerCode: '',
        userId: '',
        assignorId: '',
        productType: '',
        desc: '',
        details: []
      }
      this.reNewMode = false
    },
    // 重新创建工单
    async reNewTask (id) {
      this.reNewMode = true
      this.infoTaskShow = false
      this.$emit('update:dialogModel', 'new')
      const { data } = await getTaskInof(id)
      this.$emit('update:taksInfo', data)
      this.newTaskForm.assignorId = this.taksInfo.assignorId
      this.newTaskForm.innerCode = this.taksInfo.innerCode
      this.newTaskForm.productType = this.taksInfo.productTypeId
      this.newTaskForm.desc = this.taksInfo.desc
      this.getTaskDetails(id, true)
    },
    // 取消工单
    closeTask (taskID) {
      this.$confirm(
        '<i class="el-icon-warning" style="color: #ff665f;"></i>&nbsp;&nbsp;取消工单后，将不能恢复，是否确认取消？',
        {
          center: true,
          dangerouslyUseHTMLString: true
        }
      )
        .then(async () => {
          await taskCancel(taskID)
          this.closeFn()
          this.$emit('update')
        })
        .catch(() => {
          // 留着不给报错
        })
    },
    // 发送工单
    async pushTask () {
      if (!this.newTaskForm.details.length) {
        this.$message.error('未填写补货数量')
      } else {
        try {
          await this.$refs.newTaskForm.validate()
          await postTask(this.newTaskForm)
          this.$message.success('提交成功')
        } catch (e) {
          if (e.response.data) {
            this.$message.error(e.response.data)
          } else {
            this.$message.error('出现错误')
            console.log(e)
          }
        } finally {
          this.closeFn()
        }
      }
    },
    // 获取工单信息
    async getTaskDetails (TaskID, rec = false) {
      const { data } = await getTaskDetails(TaskID)
      this.taskDetailsData = data
      if (rec) {
        this.tempDetails = data.map(item => ({
          maxCapacity: 10,
          currentCapacity: item.expectCapacity,
          sku: {
            skuName: item.skuName,
            skuId: item.skuId,
            skuImage: item.skuImage
          },
          detailsId: item.detailsId,
          channelCode: item.channelCode
        }))
        this.newTaskForm.details = data
        // this.newTaskForm.details = data.map(item => [{
        //   currentCapacity: item.expectCapacity,
        //   skuName: item.skuName,
        //   skuId: item.skuId,
        //   skuImage: item.skuImage,
        //   detailsId: item.detailsId,
        //   channelCode: item.channelCode
        // }])
      } else {
        this.infoTaskShow = true
      }
    },
    // 获取工单配置
    async postSupplyAlertValue () {
      const { data: supplyAlertValueData } = await supplyAlertValue()
      this.supplyAlertValue.number = supplyAlertValueData
    },
    // 保存工单配置
    async settingSaveFn () {
      await autoSupplyConfig(this.supplyAlertValue.number)
      this.closeFn()
    },
    // 获取新建工单的运营人员
    async getNewTaskUser (id) {
      const { data } = await newTaskUser(id)
      this.operatorList = data
    },
    // 获取新建工单的运营人员输入框值
    newTaskUser (val) {
      if (val !== ' ' && val.length) {
        if (this.timeOut) clearTimeout(this.timeOut)
        this.timeOut = setTimeout(() => {
          this.getNewTaskUser(val)
        }, 500)
      }
    },
    // 补货清单 如果val是false就是编辑模式
    async getChannelList (id, rec = false) {
      if (id) {
        // 判断是不是编辑模式
        const { data } = await getChannelList(id)
        if (rec) {
          this.tempDetails = data
          this.newTaskForm.details = data
        } else if (this.newTaskForm.details.length === 0) { // 判断是否已经保存过
          this.tempDetails = data
        }
        this.infoTaskShow = true
      } else {
        this.$message('需要先输入设备编号')
      }
    },
    // 补货清单被确认操作
    pushTempDetails () {
      this.infoTaskShow = false
      this.newTaskForm.details = this.tempDetails.filter(item => item.sku).map(item => {
        return {
          channelCode: item.channelCode,
          expectCapacity: item.currentCapacity,
          skuId: item.sku.skuId,
          skuImage: item.sku.skuImage,
          skuName: item.sku.skuName
        }
      })
    },
    // 测试用
    test (val) {
      console.log(val)
    }
  },
  watch: {
    // 检测到显示方式变化就请求数据
    visible (newStr) {
      this.newTaskForm.userId = this.$store.state.user.userId
      console.log(this.$store.state)
      if (newStr === true) {
        if (!(this.dialogModel === 'info') && !this.reNewMode) this.$emit('update:taksInfo', {})
        if (this.dialogModel === 'setting') this.postSupplyAlertValue()
      }
    },
    infoTaskShow (newStr) {
      // 重置清单
      if (newStr === false) {
        this.taskDetailsData = []
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.el-dialog__body {
  padding: 20px;
}
.infos{
  ::v-deep .number.el-input-number, ::v-deep  .el-input, .el-textarea {
    width: 396px;
  }

}
.table.newTask {
  margin-right: 1em;
  .el-input-number,.el-input{
    width: 100%;
  }
}
.el-textarea textarea {
  height: 6em;
}
.showShowNeed {
  .header {
    display: flex;
    align-items: center;
    height: 54px;
    margin-bottom: 25px;
    background: #f8f8f8;
    .icon {
      img {
        width: 26px;
        height: 26px;
        margin-left: 22px;
      }
    }
    .title {
      flex: 1;
      margin-left: 16px;
      color: #242525;
    }
    .pic {
      margin-right: 76px;
      margin-bottom: 7px;
    }
  }
  .info {
    color: #606266;
    display: flex;
    font-size: 13px;
    .row {
      height: 36px;
      flex: 50%;
      display: flex;
      align-items: center;
    }
    .col {
      display: flex;
      flex-wrap: wrap;
    }
    .title {
      width: 120px !important;
      text-align: end;
      padding-right: 12px;
    }
  }
}
.table {
  height: 400px;
  .el-table {
    font-size: 13px;
    .el-table__header-wrapper {
      .cell {
        padding: 10px 0 10px 10px !important;
        font-weight: 400 !important;
        background: #f3f6fb;
        color: #666;
      }
    }
    .el-table__cell {
      padding: 0;
      border: none;
      .cell {
        padding: 5px 0 10px 10px;
      }
    }
  }
}
</style>
